package cn.itlaobing.web.servlet;

import cn.itlaobing.entity.Goods;
import cn.itlaobing.entity.ShopCart;
import cn.itlaobing.service.GoodsService;
import cn.itlaobing.web.annotation.RequestMapping;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/20 0020.
 */
@WebServlet("/shopCart/*")
public class ShopCartServlet extends BaseServlet{

    @RequestMapping("/show")
    public void showCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        toView(request,response,"/shopCart/show");
    }

    @RequestMapping("/updateCount")
    public void updateCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsId=request.getParameter("goodsId");
        String count=request.getParameter("count");

        //从Session中取出购物车
        ShopCart shopCart=(ShopCart)(request.getSession().getAttribute("shopCart"));
        if(shopCart!=null){
            shopCart.updateCount(Integer.valueOf(goodsId),Integer.valueOf(count));
            Map<String,Object> map=new HashMap<>();
            map.put("success",true);
            map.put("total",shopCart.getTotalPrice());
            String result= JSON.toJSONString(map);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(result);
        }else{
            Map<String,Object> map=new HashMap<>();
            map.put("success",false);
            String result= JSON.toJSONString(map);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(result);
        }


    }



    @RequestMapping("/add")
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取商品的id
        String goodsId=request.getParameter("goodsId");
        GoodsService goodsService=new GoodsService();
        Goods goods= goodsService.findById(Integer.valueOf(goodsId));


        ShopCart shopCart=(ShopCart)(request.getSession().getAttribute("shopCart"));
        if(shopCart==null){
            shopCart=new ShopCart();
            //购物车放入session
            request.getSession().setAttribute("shopCart",shopCart);
        }

        shopCart.add(goods);
       // redirectTo(response,"/shopCart/show");
        response.sendRedirect(request.getContextPath()+"/shopCart/show");
    }
}
